<?php

namespace app\admin\controller\device;

use app\common\model\School;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 班牌设备
 *
 * Class Device
 * @package app\admin\controller\device
 */
class Device extends Backend
{
    /**
     * @var \app\common\model\Device
     */
    protected $model = null;
    protected $searchFields = 'id,name';
    protected $noNeedRight = ['searchlist', 'detail'];
    protected $schoolLimit = true;
    protected $schoolIds = [];

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Device');

        if ($this->auth->isSuperAdmin()) {
            $schoolList = collection(School::all())->toArray();
        } else {
            $this->schoolIds = $this->auth->getChildrenSchoolIds(true);
            $schoolList = collection(School::where('id', 'in', $this->schoolIds)->select())->toArray();
        }
        $schoolTree = new Tree();
        $schoolTree->init($schoolList);
        $schooldata = [];

        if ($this->auth->isSuperAdmin()) {
            $school_result = $schoolTree->getTreeList($schoolTree->getTreeArray(0));
            foreach ($school_result as $k => $v) {
                $schooldata[$v['id']] = $v['name'];
            }

        } else {
            $school_childlist = $schoolTree->getTreeList($schoolTree->getTreeArray($this->auth->school_id));

            $school_result = [];
            foreach ($school_childlist as $k => $v) {
                $school_result[$v['id']] = $v['name'];
            }
            $schooldata = $school_result;
        }

        $this->view->assign('schoolData', $schooldata);

    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $count = \app\common\model\Device::where('school_id', $params['school_id'])->count();
                if ($count) {
                    $this->error('该部门下已添加过了');
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if (isset($params['expired_at'])) {
                        $params['expired_at'] = strtotime($params['expired_at']);
                    }
                    $result = $this->model->allowField(true)->save($params);

//                    if ($result) {
//                        $device_key = new \app\common\model\DeviceKey();
//
//                        $insert_data = [];
//                        for ($i = 0; $i < $params['count']; $i++) {
//                            $insert_data[] = [
//                                'device_id' => $this->model->id,
//                                'key' => unique()
//                            ];
//                        }
//
//                        $result = $device_key->saveAll($insert_data);
//                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $schoolIds = $this->getDataLimitSchoolIds();
        if (is_array($schoolIds)) {
            if (!in_array($row[$this->schoolLimitField], $schoolIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $count = $params['count'] - $row['count'];

                if ($count < 0) {
                    $this->error(__('激活码数量不能小于原来数量'));
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    /*if ($result && $count) {

                        $device_key = new \app\common\model\DeviceKey();
                        $insert_data = [];
                        for ($i = 0; $i < $count; $i++) {
                            $insert_data[] = [
                                'device_id' => $row['id'],
                                'key' => strtoupper(md5(uuid()))
                            ];
                        }

                        $result = $device_key->saveAll($insert_data);
                    }*/

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function detail()
    {
        $device = \app\common\model\Device::where('school_id', $this->auth->school_id)->find();

        if (!$device) {
            $device['count'] = 0;
            $device['used_count'] = 0;
        }
        return json($device);
    }


}